from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_execute_widget import Ui_widget_execute
from app.window.msg_box import Msg_box
import time
from worker.ssh_worker import Ssh_worker

class Script_signal(QObject):
    new_script = Signal()
    remove_script = Signal()
    update_script = Signal()
    group_changed_script = Signal(str)
    select_changed_script = Signal(str)

    new_device = Signal()
    remove_device = Signal()
    update_device = Signal()
    group_changed_device = Signal(str)
    select_changed_device = Signal(str)
    # get_device_info = Signal(str)

    exectue_script = Signal(dict)

    script_manager = Signal(int)

    send_logs = Signal(str)

class Script_widget(QWidget):
    
    cur_item: QListWidgetItem = None
    signal = Script_signal()
    def __init__(self, parent=None):
        super(Script_widget, self).__init__(parent)
        self.ui = Ui_widget_execute()
        self.ui.setupUi(self)

        self.disable_btn = False
        self.timer = QTimer()
        self.timer_ip = ''
        self.timer_time = 1
        self.timer.timeout.connect(self.connect_time)
        self.msg = Msg_box(self)

        self.init_clicked_event()


    def init_clicked_event(self):

        self.ui.pushButton_exec.clicked.connect(self.execute_script)
        self.ui.listWidget_script.itemClicked.connect(self.click_item)
        # self.ui.pushButton_script_manager.clicked.connect(self.open_script_manager)
        self.ui.pushButton_clear_data.clicked.connect(self.clear_data)

    def execute_script(self):
        if self.disable_btn:
            QMessageBox.warning(self, "警告", "正在执行任务,请勿重新执行!", QMessageBox.Yes)
            return
        if self.ui.textEdit_script_show.toPlainText() == '':
            QMessageBox.warning(self, "警告", "脚本不为空!", QMessageBox.Yes)
            return
        
        script_item = self.ui.listWidget_script.currentItem()
        script_name = '无'
        if  script_item is not None :
            script_name = script_item.text()
        current_time = time.localtime()
        fmt_time = time.strftime('%Y-%m-%d %H:%M:%S',current_time)
        log_data = {
            'device_name': self.ui.lineEdit_device_name.text(),
            'script_name': script_name,
            'cmds' : self.ui.textEdit_script_show.toPlainText(),
            'ip' : self.ui.lineEdit_device_ip.text(),
            'port' : self.ui.lineEdit_port.text(),
            'user':self.ui.lineEdit_user.text(),
            'password':self.ui.lineEdit_password.text(),
            'supplier':self.ui.lineEdit_device_supplier.text(),
            'model' : self.ui.lineEdit_device_model.text(),
            'position' : self.ui.lineEdit_device_position,
            'exec_time':fmt_time,
        }
        ssh_data = {
            'ip' : self.ui.lineEdit_device_ip.text(),
            'port' : self.ui.lineEdit_port.text(),
            'user':self.ui.lineEdit_user.text(),
            'password':self.ui.lineEdit_password.text(),
            'cmds' : self.ui.textEdit_script_show.toPlainText(),
            'textfsm':self.ui.textEdit_TextFSM.toPlainText(),

            'device_name': self.ui.lineEdit_device_name.text(),
            'script_name': self.ui.listWidget_script.currentItem().text()
        }
        
        # 线程
        self.workerThread = QThread(self)
        self.workerThread.setObjectName('workerThread')
        self.worker = Ssh_worker(ssh_data)
        self.worker.moveToThread(self.workerThread)
        self.workerThread.started.connect(self.worker.start_work)
        self.worker.finished.connect(self.workerThread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.worker.finished.connect(self.task_done)
        self.worker.signal.send_logs.connect(self.send_logs)
        # self.worker.signal.timer_stop.connect(self.timer_stop)
        self.workerThread.finished.connect(self.workerThread.deleteLater)

        self.workerThread.start()

        # 信息输出
        self.timer_ip = ssh_data["ip"]
        self.timer_time = 1
        # self.timer.start(1000)

        self.disable_btn = True


    def task_done(self):
        self.disable_btn = False
        # self.ssh_thd = None

    def timer_stop(self):
        self.timer.stop()

    def connect_time(self):
        log_text = f'正在连接服务器:{self.timer_ip} {self.timer_time} 秒'
        self.signal.send_logs.emit(log_text)
        self.timer_time += 1

    def send_logs(self,logs:str):
        self.signal.send_logs.emit(logs)

    # 脚本
    def new_script(self):
        self.signal.new_script.emit()

    def remove_script(self):
        if self.cur_item is None:
            return
        self.cur_item = self.ui.listWidget_script.currentItem()
        if self.cur_item.isSelected():
            self.ui.listWidget_script.removeItemWidget(self.cur_item)
        self.cur_item = None
        self.signal.remove_script.emit()

    def update_script(self):
        if self.cur_item is None:
            return
        self.signal.update_script.emit()

    def group_changed_script(self,item_text:str):
        self.signal.group_changed_script.emit(item_text)

    def select_changed_script(self,current:QListWidgetItem,previous:QListWidgetItem):
        if current == None or previous == None or current == previous:
            return
        self.signal.select_changed_script.emit(previous.text())

    # 设备
    def update_script_config(self,data:dict):
        self.config_data = data

        self.ui.lineEdit_device_name.setText(data['device']['name'])
        self.ui.lineEdit_device_ip.setText(data['device']['ip'])
        self.ui.lineEdit_port.setText(str(data['device']['port']))
        self.ui.lineEdit_user.setText(data['device']['user'])
        self.ui.lineEdit_password.setText(data['device']['password'])
        self.ui.lineEdit_device_supplier.setText(data['device']['supplier'])
        self.ui.lineEdit_device_model.setText(data['device']['model'])
        self.ui.lineEdit_device_position.setText(data['device']['position'])

        # 加载脚本信息
        self.ui.textEdit_script_show.clear()
        self.ui.listWidget_script.clear()
        self.script = data['script']
        if not self.script:
            return
        
        for i in range(0,len(self.script)):
            self.script[i]['item'] = QListWidgetItem(self.script[i]['name'])
            self.ui.listWidget_script.addItem(self.script[i]['item'])
        
        

        self.ui.textEdit_script_show.setText(self.script[0]['content'])
        self.ui.textEdit_TextFSM.setText(self.script[0]['textfsm'])
        self.ui.listWidget_script.setCurrentRow(0)

    def click_item(self,item:QListWidgetItem):
        self.ui.textEdit_script_show.setText(self.script[self.ui.listWidget_script.row(item)]['content'])


    def clear_data(self):
        self.config_data = None
        self.ui.lineEdit_device_name.setText('')
        self.ui.lineEdit_device_ip.setText('')
        self.ui.lineEdit_port.setText('')
        self.ui.lineEdit_user.setText('')
        self.ui.lineEdit_password.setText('')
        self.ui.lineEdit_device_supplier.setText('')
        self.ui.lineEdit_device_model.setText('')
        self.ui.lineEdit_device_position.setText('')
        self.ui.textEdit_script_show.setText('')
        self.ui.listWidget_script.clear()
